using System.Configuration;
using System.Diagnostics;

using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;

namespace SiteParser.Core.Logging
{
    /// <summary>
    /// Represents the configuration data for a <see cref="PurgingRollingFlatFileTraceListenerData"/>.
    /// </summary>	
    [Assembler(typeof(PurgingRollingFlatFileTraceListenerAssembler))]
    public class PurgingRollingFlatFileTraceListenerData : RollingFlatFileTraceListenerData
    {
        private const string PurgeIntervalDaysPropertyName = "purgeIntervalDays";
        [ConfigurationProperty(PurgeIntervalDaysPropertyName, IsRequired = false)]
        [IntegerValidator(MinValue = 0)]
        public int PurgeIntervalDays
        {
            get { return (int)this[PurgeIntervalDaysPropertyName]; }
            set { this[PurgeIntervalDaysPropertyName] = value; }
        }
    }

    /// <summary>
    /// Represents the process to build a <see cref="PurgingRollingFlatFileTraceListenerAssembler"/> described by a <see cref="PurgingRollingFlatFileTraceListenerData"/> configuration object.
    /// </summary>
    public class PurgingRollingFlatFileTraceListenerAssembler : TraceListenerAsssembler
    {
        public override TraceListener Assemble(IBuilderContext context, TraceListenerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            PurgingRollingFlatFileTraceListenerData castObjectConfiguration
                = (PurgingRollingFlatFileTraceListenerData)objectConfiguration;

            ILogFormatter formatter = GetFormatter(context, castObjectConfiguration.Formatter, configurationSource, reflectionCache);

            PurgingRollingFlatFileTraceListener createdObject
                = new PurgingRollingFlatFileTraceListener(
                    castObjectConfiguration.FileName,
                    castObjectConfiguration.Header,
                    castObjectConfiguration.Footer,
                    formatter,
                    castObjectConfiguration.RollSizeKB,
                    castObjectConfiguration.TimeStampPattern,
                    castObjectConfiguration.RollFileExistsBehavior,
                    castObjectConfiguration.RollInterval,
                    castObjectConfiguration.PurgeIntervalDays
                    );

            return createdObject;
        }
    }
}
